package com.grm.service.impl;

import com.grm.mapper.ProductRepository;
import com.grm.model.Product;
import com.grm.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductRepository productRepository;

    // 创建或更新产品
    @Override
    public Product saveProduct(Product product) {
        return productRepository.save(product);
    }

    // 根据 ID 查询产品
    @Override
    public Optional<Product> findById(String id) {
        return productRepository.findById(id);
    }

    // 根据名称查询产品+分页
    @Override
    public List<Product> findByName(String name) {
        return productRepository.findByNameContaining(name, PageRequest.of(0, 2));
        // return productRepository.findByNameContaining(name);
    }

    // 获取所有产品
    @Override
    public Page<Product> findAll(Pageable pageable) {
        return productRepository.findAll(pageable);
    }

    // 删除产品
    @Override
    public void deleteProduct(String id) {
        productRepository.deleteById(id);
    }
}
